// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Login    from '@/views/Login.vue'
import Layout   from '@/layout/index.vue'
import master   from '@/router/modules/master'
import registry from '@/router/modules/registry'
import doctor   from '@/router/modules/doctor'
import lab      from '@/router/modules/lab'
import { useCounterStore } from '@/stores/counter'

// 所有用户都能访问的路由
const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    meta: { title: '首页', icon: 'HomeOutlined' },
    children: []  // 这里留空，后面动态挂载
  }
]

const asyncRouteMap = {
  0: [ master, registry, doctor, lab ], // root
  1: [ master ],                        // 系统管理员
  2: [ registry ],                      // 挂号收费员
  3: [ doctor ],                        // 门诊医生
  4: [ lab ]                            // 检验医生
}

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

let added = false

router.beforeEach((to, from, next) => {
  const counter = useCounterStore()
  const type    = counter.useType
  console.log('[ROUTE GUARD] useType =', counter.useType)
  // 登录后，useType 不为空，且还没加过动态路由
  if (type != null && !added) {
    const allow = asyncRouteMap[type] || []
    // 把每个模块路由添加到 Layout 这个父路由下
    allow.forEach(r => router.addRoute('Layout', r))
    added = true
    // 重新导航一次以应用新路由
    return next({ ...to, replace: true })
  }

  // 未登录且要访问非 /login，就跳登录页
  if (type == null && to.path !== '/login') {
    return next('/login')
  }

  next()
})

export default router
